<?php


namespace App\Http\Services;

use App\Exceptions\BusinessException;
use App\Models\Dept;
use App\Models\Dict;
use App\Models\DictItem;

use Illuminate\Support\Facades\DB;

class DictService extends BaseService
{

    public function all(){
        $result = Dict::orderBy('sort','asc')->orderBy('id','desc')->get();
        return $result->transform(function($item){
            return [
                'id'=>$item->id,
                'name'=>$item->name,
                'value'=>$item->value
            ];
        });
    }

    public function tree(){
        $departments = Dict::where('status',1)->orderBy('sort','asc')->get()->toArray();

        $dept = $this->buildTree($departments);

        return $dept;
    }


    public function options($type){
        $dict = Dict::with(['dict_items'=>function($q){
            $q->where('status',1)->orderBy('sort','asc')->select(['id','dict_id','name','value','sort','status']);
        }])->where('code',$type)->first();
        $packDict = [];
        if($dict->dict_items){
            foreach ($dict->dict_items as  $key => $item){
                $packDict[$key]['label'] = $item->name;
                $packDict[$key]['value'] = $item->value;
            }
        }
        return $packDict;
    }

    public function list($params=[])
    {
        $model = Dict::with(['dict_items'=>function($q){
            $q->where('status',1)->orderBy('sort','asc')->select(['id','dict_id','name','value','sort','status']);
        }])->whereNull('deleted_at');
        if(isset($params['name'])){
            $model->where('name','like','%'.$params['name'].'%');
        }
        $list = $model->orderBy('id','desc')->paginate();
        return $list;
    }

    public function store($params=[],$id=0)
    {
        $dict = null;
        if($id>0) {
            $dict = Dict::where('id', $id)->first();
            if (empty($dict)) {
                throw new BusinessException('未查询到数据');
            }
            $repeat = Dict::where('id', '<>', $id)->where(function($q) use ($params){
                $q->where('name',$params['name']);
            })->first();
            $repeat2 = Dict::where('id', '<>', $id)->where(function($q) use ($params){
                $q->where('code',$params['code']);
            })->first();
        }else{
            $repeat = Dict::where(function($q) use ($params){
                $q->where('name',$params['name']);
            })->first();
            $repeat2 = Dict::where(function($q) use ($params){
                $q->where('code',$params['code']);
            })->first();
        }

        if ($repeat || $repeat2) {
            throw new BusinessException('数据重复');
        }

        $add = [];
        $add["code"]=$params['code'];
        $add["name"]= $params['name'];
        $add["status"]= $params['status'] ?? 1;
        $add["remark"]= $params['remark'] ?? null;


        if(hasDuplicateKey($params['dictItems'] ?? [],'name')){
            throw new BusinessException('字典项名称不能重复');
        }

        if(hasDuplicateKey($params['dictItems'] ?? [],'value')){
            throw new BusinessException('字典项值不能重复');
        }


        DB::beginTransaction();
        if(empty($dict)){
            $addResult = Dict::create($add);
            if($addResult === false){
                DB::rollBack();
            }
            if($params['dictItems']){
                foreach ( $params['dictItems'] as  $item) {
                    $addItem = [];
                    $addItem["name"] = $item['name'];
                    $addItem["value"] = $item['value'] ?? null;
                    $addItem["sort"] = $item['sort'] ?? 0;
                    $addItem["status"] = $item['status'] ?? 1;
                    $addItem["remark"] = $item['remark'] ?? null;
                    $addItem["dict_id"] = $addResult->id;
                    DictItem::create($addItem);
                }
            }
        }else{
            $updateResult = $dict->update($add);
            if($updateResult === false){
                DB::rollBack();
            }
            if($params['dictItems']){
                $successTmpIdArr = [];
                foreach ( $params['dictItems'] as  $item) {
                    $updateItem = [];
                    $updateItem["name"] = $item['name'];
                    $updateItem["value"] = $item['value'] ?? null;
                    $updateItem["sort"] = $item['sort'] ?? 0;
                    $updateItem["status"] = $item['status'] ?? 1;
                    $updateItem["remark"] = $item['remark'] ?? null;

                    if (isset($item['id'])) {
                        $dictItem = DictItem::where('id',$item['id'])->where('dict_id',$id)->first();
                        if(empty($dictItem)){
                            throw new BusinessException('数据不存在');
                        }
                        $successTmpIdArr[] = $item['id'];
                        $dictItem->update($updateItem);
                    }else{
                        $updateItem["dict_id"] = $id;
                        $addItemResult = DictItem::create($updateItem);
                        $successTmpIdArr[] = $addItemResult->id;
                    }
                }
                $deleteResult = DictItem::where('dict_id',$id)->whereNotIn('id',$successTmpIdArr)->delete();
            }else{
                $deleteResult = DictItem::where('dict_id',$id)->delete();
            }
        }
        DB::commit();

        return true;
    }

    public function show($id)
    {
        $result = Dict::with(['dict_items'=>function($q){
            $q->where('status',1)->orderBy('sort','asc')->select(['id','dict_id','name','value','sort','status']);
        }])->where('id',$id)->first();
        if(empty($result)){
            return [];
        }
        $result->dictItems = $result->dict_items;
        return $result;
    }
    /**
     * delete
     */
    public function destroy($id)
    {
        $dept = Dict::find($id);
        if(empty($dept)){
            throw new BusinessException('数据不存在');
        }
        $result = Dict::where('id','=',$id)->delete();
        if($result === false){
            throw new BusinessException('删除失败');
        }
        $deleteDictItem = DictItem::where('dict_id',$id)->delete();
        return $result;
    }



}
